#include "nibbles.h"

Nibbles::Nibbles()
{
    this->resize(800,700);
    footLen = 40;
    maxLen = 3 ;
    dire = D_RIGHT;
    qsrand(QTime::currentTime().msec());
    timer = new QTimer(this);
    timer->setInterval(800);
    timer->start();
    snake.push_back(getFood());
    food = getFood();

    QObject::connect(timer,SIGNAL(timeout())
                     ,this,SLOT(snakeMove()));
}

Nibbles::~Nibbles()
{

}

QLabel* Nibbles::getFood()
{
    food = new QLabel(this);
    food->resize(footLen,footLen);
    food->setAutoFillBackground(true);
    food->setPalette(QPalette(QColor(qrand()%256,qrand()%256
                                     ,qrand()%256)));
    int w = this->width() - footLen;
    int h = this->height() - footLen;

    food->move((qrand()%w/footLen)*footLen ,
               (qrand()%h/footLen)*footLen);

    food->show();
    return food;
}

void Nibbles::keyPressEvent(QKeyEvent *e)
{

    switch(e->key())
    {
        case Qt::Key_Up:
            dire = D_UP;
        break;
        case Qt::Key_Down:
            dire = D_DOWN;
        break;
        case Qt::Key_Left:
            dire = D_LEFT;
        break;
        case Qt::Key_Right:
            dire = D_RIGHT;
        break;
    }
}

void Nibbles::snakeMove()
{
    int sx = snake[0]->x();
    int sy = snake[0]->y();

    /* justfy if the head of snake covers the food */
    if(sx == food->x() && sy == food->y())
    {
        snake.push_back(food);
        food = getFood();
    }

    for(int i = snake.size() - 1 ; i > 0 ; i--)
    {
        snake[i]->move(snake[i-1]->x(),snake[i-1]->y());
    }

    /* if the snake touches the edge of widget  */
    if(sx < 0 || sy < 0 || sx>this->width() || sy>this->height())
    {
        QMessageBox msg;
        msg.setText("Game Over");
        msg.exec();
        this->close();
    }

    switch(dire)
    {
        case D_UP:
            sy = sy - footLen;
        break;
        case D_DOWN:
            sy = sy + footLen;
        break;
        case D_LEFT:
            sx = sx - footLen;
        break;
        case D_RIGHT:
            sx = sx + footLen;
        break;
    }
    snake[0]->move(sx,sy);
}
